<script setup lang="ts">
import {computed, onBeforeMount, ref, watch} from "vue";
import {userConfigStore} from "@/store/user/userConfigStore";
import {ECode, iconFontAddress} from "@/util/commonUtil";
import {createFromIconfontCN} from "@ant-design/icons-vue";
import {getUserList} from "@/api/user/user";
import _ from "lodash";
import {message} from "ant-design-vue";
import {loginConfigStore} from "@/store/user/loginConfigStore";
import {v4 as uuidV4} from 'uuid';
import {dateFormat} from "@/util/commentUtil";
import {Fancybox} from "@fancyapps/ui";

const props = defineProps({
  // 是否显示头像
  showAvatar: {
    type: Boolean,
    default: true
  },
  userInfo: {
    type: Object
  },
  // 回复的对象
  toInfo: {
    type: Object
  },
  // 博客信息
  commentInfo: {
    type: Object
  },
  showCancel: {
    type: Boolean,
    default: true
  },
  commentFinish: {
    type: Boolean,
    default: false
  }
});

const IconFont = createFromIconfontCN({
  scriptUrl: iconFontAddress,
});

const inputContent = ref<any>(null)
const comments = ref<any>([])
const userList = ref<any>([])
const userListMention = ref<any>([])
const isShowAvatar = ref<boolean>(true)
const authCode = ref<any>([])
const getUserPhoto = computed(() => userConfigStore().getUserPhoto)
const isLogin = computed(() => userConfigStore().isLogin)
const emit = defineEmits(['submit-box','show-cancel'])

onBeforeMount(() => {
  authCode.value = computed(() => userConfigStore().authCode)
})
watch(() => userConfigStore().authCode, () => {
  authCode.value = computed(() => userConfigStore().authCode)
})
watch(() => inputContent.value, () => {
  if (inputContent.value === "@" || inputContent.value.indexOf("@") !== -1) {
    querySearchAsync('')
  }
})
watch(() => props.commentFinish, () => {
  inputContent.value = ''
})

async function querySearchAsync(queryString: any) {
  let params: any = {}
  params.currentPage = 1;
  params.pageSize = 10;
  params.keyword = queryString
  params.orderByDescColumn = "credits"
  userListMention.value = []
  await getUserList(params).then((resp: any) => {
    if (resp.code === ECode.SUCCESS) {
      userList.value = resp.data.records
      userListMention.value.push(...resp.data.records.map((item: any) => ({
        value: item.nickName,
        label: item.nickName
      })))
    }
  })
}

function handleSubmit() {
  if (_.isNull(inputContent.value) || inputContent.value.trim() == '') {
    message.warning('请输入评论内容！')
    return
  }
  let info: any = userConfigStore().userInfo
  let isLogin: any = userConfigStore().isLogin
  let content: any = inputContent.value
  if (!isLogin) {
    message.warning('登录后才可以评论哦！')
    // 未登录，自动弹出登录框
    loginConfigStore().setLoginMessage(uuidV4())
    return
  }
  if (inputContent.value.length > 2048) {
    message.error('评论字符过多，已超过2048个字符')
    return
  }
  let userUid = info.uid;
  let toUserUid = "";
  let toCommentUid = "";
  let blogUid = "";
  // 评论来源： MESSAGE_BOARD，ABOUT，BLOG_INFO 等 代表来自某些页面的评论
  let source = "";
  if (props.toInfo) {
    toUserUid = props.toInfo.uid;
    toCommentUid = props.toInfo.commentUid;
  }
  if (props.commentInfo) {
    blogUid = props.commentInfo.blogUid;
    source = props.commentInfo.source;
  }
  comments.value = {
    userUid: userUid,
    toCommentUid: toCommentUid,
    toUserUid: toUserUid,
    content: content,
    blogUid: blogUid,
    source: source,
    reply: [],
  }
  comments.value.createTime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
  emit("submit-box", comments.value)
}

function showCancelEmit(){
  emit('show-cancel', false)
}

function handleLogin(){
  if (Fancybox.name){
    Fancybox.close()
  }
  loginConfigStore().setLoginMessage(uuidV4())
}
</script>

<template>
  <div class="commentBox h-[300px] comment-respond w-full relative" id="commentBox">
    <div class="commentBoxMain">
      <a-row :gutter="[16,16]">
        <a-col :span="24">
          <div class="commentInputContainer min-h-40">
            <a-comment class="relative">
              <template #avatar>
                <span class="leftAvatar lg:relative" v-if="isShowAvatar">
                  <a-avatar v-if="getUserPhoto" size="large" class="h-10 w-10 flex items-center justify-center"
                            :src="getUserPhoto"
                            style="border: var(--vip-border)"/>
                  <a-avatar v-else size="large" class="h-10 w-10 flex items-center justify-center"
                            style="border: var(--vip-border)">
                    <IconFont type="icon-morentouxiang"/>
                  </a-avatar>
                </span>
              </template>
              <template #content>
                <a-form-item>
                  <a-mentions
                      autofocus
                      name="comment"
                      style="grid-area: comment;min-height: 12em;transition: 0s;"
                      :options="userListMention"
                      v-model:value="inputContent"
                      class="chat-input-div rounded"
                      placeholder="既然来了，那就留下些什么吧~"
                      rows="8">
                  </a-mentions>
                </a-form-item>
                <a-form-item class="commentBoxBottom flex float-right">
                  <a-button v-if="showCancel" @click="showCancelEmit" class="mr-2">取消评论</a-button>
                  <a-button class="comment-submit" :disabled="authCode.ADD_COMMENT"
                            type="primary"
                            v-if="isLogin"
                            @click="handleSubmit">发表评论
                  </a-button>
                  <a-button class="comment-submit"
                            type="primary"
                            danger
                            v-if="!isLogin"
                            @click="handleLogin">立即登录
                  </a-button>
                </a-form-item>
              </template>
            </a-comment>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<style scoped lang="less">
@media (max-width: 1024px) {
  .leftAvatar{
    position: absolute;
    bottom: 20px;
    left: 12px;
  }
}
</style>
